package org.zad1;

public abstract class FunUtil {

	static boolean czyZbalansowana(String fun)
	{
		int one = 0;
		int zero = 0;
		
		for(int i=0; i < fun.length(); i++)
		{
			if(fun.charAt(i) == '0')
				zero++;
			else
				one++;
		}
		return (one == zero ? true : false);
	}
	
	static int rzadNieliniowosci(String fun, Afiniczne afiniczne)
	{
		int min = -1;
		for(int i=0; i< afiniczne.size(); i++)
		{
			int distance = distance(fun, afiniczne.get(i));
			if(distance < min || min == -1)
				min = distance;
		}
		return min;
	}
	
	static int procentJedynek(String fun)
	{
		int one = 0;
		
		for(int i=0; i < fun.length(); i++)
		{
			if(fun.charAt(i) == '1')
				one++;
		}
		int result = (one * 100)/fun.length();
		if(result < 50)
			result = 100 - result;
		return result;
	}
	
	static boolean spelniaSAC(String funkcja, int liczbaArgumentow)
	{
		StringBuilder alfa = new StringBuilder("");
		boolean returnValue = true;
		for(int i=0; i< liczbaArgumentow; i++)
			alfa.append("0");
		
		for(int i=0; i< liczbaArgumentow; i++)
		{
			alfa.setCharAt(i, '1');
			if(i!=0)
				alfa.setCharAt(i-1, '0');
			
			StringBuilder fun_result = new StringBuilder();
			
			for(int fun_index=0; fun_index< funkcja.length(); fun_index++)
			{
				String valueAt = "00000000" + Integer.toString(fun_index, 2);
				valueAt = valueAt.substring(valueAt.length()-liczbaArgumentow, valueAt.length());
				valueAt = sumMod2(valueAt, alfa.toString());
				
				fun_result.append(funkcja.charAt(Integer.parseInt(valueAt, 2)));
			}
			String result = sumMod2(funkcja, fun_result.toString());
			int oneProc = procentJedynek(result);
			System.out.println(oneProc);
			if(oneProc> 51)
				returnValue = false;
		}
		return returnValue;
	}
	
	static String getBit(int value, int bitNumber)
	{
		if ((value & (1 << bitNumber)) != 0)
			return "1";
		else
			return "0";
	}
	
	static String sumMod2(String one, String two)
	{
		String result = "";
		if(one.length() == two.length())
		{
			for(int i = 0; i< one.length(); i++)
			{
				int one_i = one.charAt(i);
				int two_i = two.charAt(i);
				
				result += ( one_i + two_i ) % 2;
			}
		}
		return result;
	}
	
	static int distance(String one, String two)
	{
		int distance = 0;
		
		if(one.length() == two.length())
		{
			for(int i=0; i< one.length(); i++)
			{
				int fun1_int = one.charAt(i);
				int fun2_int = two.charAt(i);
				
				int result = (fun1_int + fun2_int)%2;
				distance += result;
			}
			return distance;
		}
		return -1;
	}
}
